package controller

import (
	"strconv"

	"github.com/gogf/gf/v2/net/ghttp"

	"goldtree/internal/service"
	"goldtree/utility/response"
)

// DataQueryController 数据查询控制器
type DataQueryController struct{}

var DataQueryCtrl = DataQueryController{}

// QueryStocks 查询股票数据
func (c *DataQueryController) QueryStocks(r *ghttp.Request) {
	var req *service.StockQueryReq
	if err := r.Parse(&req); err != nil {
		response.ErrorExit(r, "参数解析失败: "+err.Error())
		return
	}

	result, err := service.DataQuery.QueryStocks(r.Context(), req)
	if err != nil {
		response.ErrorExit(r, err.Error())
		return
	}

	response.PageExit(r, result.List, result.Total, result.Page, result.Limit)
}

// QueryKLineData 查询K线数据
func (c *DataQueryController) QueryKLineData(r *ghttp.Request) {
	var req *service.KLineQueryReq
	if err := r.Parse(&req); err != nil {
		response.ErrorExit(r, "参数解析失败: "+err.Error())
		return
	}

	result, err := service.DataQuery.QueryKLineData(r.Context(), req)
	if err != nil {
		response.ErrorExit(r, err.Error())
		return
	}

	response.SuccessExit(r, result)
}

// QueryMarketData 查询市场数据
func (c *DataQueryController) QueryMarketData(r *ghttp.Request) {
	var req *service.MarketDataQueryReq
	if err := r.Parse(&req); err != nil {
		response.ErrorExit(r, "参数解析失败: "+err.Error())
		return
	}

	result, err := service.DataQuery.QueryMarketData(r.Context(), req)
	if err != nil {
		response.ErrorExit(r, err.Error())
		return
	}

	response.SuccessExit(r, result)
}

// QuerySignals 查询交易信号
func (c *DataQueryController) QuerySignals(r *ghttp.Request) {
	var req *service.SignalQueryReq
	if err := r.Parse(&req); err != nil {
		response.ErrorExit(r, "参数解析失败: "+err.Error())
		return
	}

	result, err := service.DataQuery.QuerySignals(r.Context(), req)
	if err != nil {
		response.ErrorExit(r, err.Error())
		return
	}

	response.PageExit(r, result.List, result.Total, result.Page, result.Limit)
}

// GetStockDetail 获取股票详情
func (c *DataQueryController) GetStockDetail(r *ghttp.Request) {
	code := r.Get("code").String()
	if code == "" {
		response.ErrorExit(r, "股票代码不能为空")
		return
	}

	// 获取股票基本信息
	stock, err := service.Stock.GetByCode(r.Context(), code)
	if err != nil {
		response.ErrorExit(r, err.Error())
		return
	}
	if stock == nil {
		response.ErrorExit(r, "股票不存在")
		return
	}

	// 获取股票标签
	tags, err := service.Tag.GetStockTags(r.Context(), code)
	if err != nil {
		response.ErrorExit(r, err.Error())
		return
	}

	// 构建响应数据
	result := map[string]interface{}{
		"stock": stock,
		"tags":  tags,
	}

	response.SuccessExit(r, result)
}

// GetMarketOverview 获取市场概览
func (c *DataQueryController) GetMarketOverview(r *ghttp.Request) {
	market := r.Get("market").String()
	
	// 获取市场股票数量
	req := &service.StockQueryReq{
		Market: market,
		Limit:  1, // 只需要统计数量
	}
	
	result, err := service.DataQuery.QueryStocks(r.Context(), req)
	if err != nil {
		response.ErrorExit(r, err.Error())
		return
	}

	// 获取市场数据
	marketReq := &service.MarketDataQueryReq{
		Market: market,
		Limit:  10, // 获取前10只股票作为示例
	}
	
	marketData, err := service.DataQuery.QueryMarketData(r.Context(), marketReq)
	if err != nil {
		response.ErrorExit(r, err.Error())
		return
	}

	overview := map[string]interface{}{
		"market":      market,
		"stock_count": result.Total,
		"sample_data": marketData,
	}

	response.SuccessExit(r, overview)
}

// GetIndustryOverview 获取行业概览
func (c *DataQueryController) GetIndustryOverview(r *ghttp.Request) {
	industry := r.Get("industry").String()
	if industry == "" {
		response.ErrorExit(r, "行业不能为空")
		return
	}
	
	// 获取行业股票数量
	req := &service.StockQueryReq{
		Industry: industry,
		Limit:    1, // 只需要统计数量
	}
	
	result, err := service.DataQuery.QueryStocks(r.Context(), req)
	if err != nil {
		response.ErrorExit(r, err.Error())
		return
	}

	// 获取行业数据
	marketReq := &service.MarketDataQueryReq{
		Industry: industry,
		Limit:    10, // 获取前10只股票作为示例
	}
	
	marketData, err := service.DataQuery.QueryMarketData(r.Context(), marketReq)
	if err != nil {
		response.ErrorExit(r, err.Error())
		return
	}

	overview := map[string]interface{}{
		"industry":    industry,
		"stock_count": result.Total,
		"sample_data": marketData,
	}

	response.SuccessExit(r, overview)
}

// GetStatistics 获取统计数据
func (c *DataQueryController) GetStatistics(r *ghttp.Request) {
	// 简化的统计数据实现
	// 直接返回模拟数据用于前端展示
	stats := map[string]interface{}{
		"total_stocks":      150,
		"total_pools":       12,
		"total_strategies":  8,
		"active_strategies": 3,
		"system_status":     "正常",
		"last_update":       "2025-09-09 16:00:00",
	}
	
	response.SuccessExit(r, stats)
}

// SearchStocks 搜索股票
func (c *DataQueryController) SearchStocks(r *ghttp.Request) {
	keyword := r.Get("keyword").String()
	if keyword == "" {
		response.ErrorExit(r, "搜索关键字不能为空")
		return
	}

	limitStr := r.Get("limit").String()
	limit := 20
	if limitStr != "" {
		if l, err := strconv.Atoi(limitStr); err == nil && l > 0 && l <= 100 {
			limit = l
		}
	}

	req := &service.StockQueryReq{
		Keyword: keyword,
		Page:    1,
		Limit:   limit,
	}

	result, err := service.DataQuery.QueryStocks(r.Context(), req)
	if err != nil {
		response.ErrorExit(r, err.Error())
		return
	}

	response.SuccessExit(r, result.List)
}

// GetMarketList 获取市场列表
func (c *DataQueryController) GetMarketList(r *ghttp.Request) {
	markets, err := service.Stock.GetMarketList(r.Context())
	if err != nil {
		response.ErrorExit(r, err.Error())
		return
	}

	response.SuccessExit(r, markets)
}

// GetIndustryList 获取行业列表
func (c *DataQueryController) GetIndustryList(r *ghttp.Request) {
	industries, err := service.Stock.GetIndustryList(r.Context())
	if err != nil {
		response.ErrorExit(r, err.Error())
		return
	}

	response.SuccessExit(r, industries)
}

// GetRealtimeData 获取实时数据
func (c *DataQueryController) GetRealtimeData(r *ghttp.Request) {
	code := r.Get("code").String()
	if code == "" {
		response.ErrorExit(r, "股票代码不能为空")
		return
	}

	req := &service.MarketDataQueryReq{
		StockCode: code,
		Limit:     1,
	}

	result, err := service.DataQuery.QueryMarketData(r.Context(), req)
	if err != nil {
		response.ErrorExit(r, err.Error())
		return
	}

	if len(result) == 0 {
		response.ErrorExit(r, "未找到股票数据")
		return
	}

	response.SuccessExit(r, result[0])
}

// BatchGetRealtimeData 批量获取实时数据
func (c *DataQueryController) BatchGetRealtimeData(r *ghttp.Request) {
	codes := r.Get("codes").Strings()
	if len(codes) == 0 {
		response.ErrorExit(r, "股票代码列表不能为空")
		return
	}

	if len(codes) > 50 {
		response.ErrorExit(r, "一次最多查询50只股票")
		return
	}

	req := &service.MarketDataQueryReq{
		Codes: codes,
		Limit: len(codes),
	}

	result, err := service.DataQuery.QueryMarketData(r.Context(), req)
	if err != nil {
		response.ErrorExit(r, err.Error())
		return
	}

	response.SuccessExit(r, result)
}